package com.xuecheng.learning.service.impl;

import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.RestResponse;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.feignclient.MediaServiceClient;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.service.LearningService;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/3/27 18:57
 */
@Service
@Slf4j
public class LearningServiceImpl implements LearningService {
    
    @Resource
    MyCourseTablesService myCourseTablesService;
    
    @Resource
    ContentServiceClient contentServiceClient;
    
    @Resource
    MediaServiceClient mediaServiceClient;
    
    @Override
    public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
        
        // 查询课程信息
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null){
            return RestResponse.validfail("课程不存在");
        }
        
        // 是否支持试学
        String teachplan = coursepublish.getTeachplan();

        if (StringUtils.isNotEmpty(userId)){
            // 用户已登录
            // 通过我的课程表查询学习资格
            XcCourseTablesDto xcCourseTablesDto = myCourseTablesService.getLearningStatus(userId, courseId);
            String learnStatus = xcCourseTablesDto.getLearnStatus();
            if ("702002".equals(learnStatus)){
                return RestResponse.validfail("无法学习，因为没有选课或选课后没有支付");
            }else if ("702003".equals(learnStatus)){
                return RestResponse.validfail("已过期需要申请续期或重新支付");
            }else {
                // 有资格学习，要返回视频的播放地址
                // 远程调用媒资获取视频的播放地址
                RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
                return playUrlByMediaId;

            }
        }
        
        // 如果用户没有登录
        // 取出课程的收费规则
        String charge = coursepublish.getCharge();
        // 免费课程
        if ("201000".equals(charge)){
            // 有资格学习，要返回视频的播放地址
            // 远程调用媒资获取视频的播放地址
            RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
            return playUrlByMediaId;
        }


        return RestResponse.validfail("未选择该课程");
    }
}
